package com.yupi.yupao.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Peter
 * @Date: 2024-05-06-0:14
 * @Description: Pe
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    // 重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    // 每天执行，预热推荐用户
    @Scheduled(cron = "0 45 0 * * *")   //自己设置时间测试
    public void doCacheRecommendUsers(){
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");

        try{
            //只有一个线程获取到锁
                if(lock.tryLock(0,-1, TimeUnit.MILLISECONDS)){
                    for (Long userId:mainUserList) {
                        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                        String redisKey = String.format("yupao:user:recommend:%s", userId);
                        Page<User> userPage=userService.page(new Page<>(1,20),queryWrapper);
                        try {
                            redisTemplate.opsForValue().set(redisKey,userPage,300000, TimeUnit.MICROSECONDS);
                        }catch (Exception e){
                            log.error("redis error",e);
                        }
                    }
                }
        }catch (InterruptedException e){
            log.error("doCacheRecommendUser error", e);
        }finally {
            // 只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }


    }
}
